﻿using Max.PH5_2011A.IRespository;
using Max.PH5_2011A.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2011A.Service
{
    public class BaseService<T> : IBaseService<T> where T : class, new()
    {
        IBaseRespository<T> _respository;

        IUnitOfWork _unitOfWork;

        public BaseService(IBaseRespository<T> respository, IUnitOfWork unitOfWork)
        {
            _respository = respository;
            _unitOfWork = unitOfWork;
        }

        public int Delete(T t)
        {
            _respository.Detele(t);
            return _unitOfWork.SaveChanges();
        }

        public int Insert(T t)
        {
            _respository.Insert(t);
            return _unitOfWork.SaveChanges();
        }

        public IQueryable<T> Query()
        {
            var list = _respository.Query();
            return list;
        }
        public T QueryFirst(string id)
        {
            return _respository.QueryFirst(id);
        }
        public IQueryable<T> Query(int pageIndex, int pageSize, out int total)
        {
            var list = _respository.Query();
            total = list.Count();

            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }

        //Func<string>
        //Func<int, string> x = (b) => { return b.ToString(); };
        //Action<>
        //Predicate<>
        /*
         * 委托
         * 三个系统自带的委托
         * Func : 有返回值 。Func<>,最右边的为返回值数据类型，参数最多16个
         * Action：没有返回值，参数最多16个
         * Predicate：有返回值，返回bool类型，参数有且仅有一个
         * 一个自定义委托
         * delegate：返回值可有可无，参数可有可无，最多32个
         * **/
        public IQueryable<T> Query(System.Linq.Expressions.Expression<Func<T, bool>> where, int pageIndex, int pageSize, out int total)
        {
            //所有数据
            var list =_respository.Query();
            total = list.Count();

            //表达式树
            list.Where(where);

            return list;
        }

        public IQueryable<T> Query<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> sort, bool isAsc, int pageIndex, int pageSize, out int total)
        {
            var list = _respository.Query().Where(where);
            total = list.Count();
            if (isAsc)
            {
                list = list.OrderBy(sort);
            }
            else { 
                list = list.OrderByDescending(sort);
            }

            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }

        public int Update(T t)
        {
            _respository.Update(t);
            return _unitOfWork.SaveChanges();
        }
    }
}
